/*
    存储公共js方法
*/
import store from "../store/index"
import * as XLSX from 'xlsx'
import { saveAs } from 'file-saver'

/* 监听选中标签页项事件 */
export function set_tab(target_title: string, target_name: string) {
    let tabs = store.state.tabsList;
    store.dispatch("handlerTabsActiveName", target_name)
    /* 查找标签页列表是否存在当前点击的页面，不存在则推入栈，存在则跳转 */
    if (
      tabs.findIndex((item: any, index: number) => {
        return item.name == target_name;
      }) == -1
    ) {
      tabs.push({
        title: target_title,
        name: target_name,
      });
      store.dispatch("handlerTabsList", tabs);
    }

};

/* 监听删除标签页项事件 */ 
export function remove_tab(target_name: string) {
    let tabs: any = store.state.tabsList;
    if(tabs.length <= 1) return
    
    // 计算当前删除的标签项的索引
    let tab_index = tabs.findIndex((item: any) => {
      return item.name.includes(target_name)
    })
    tabs = tabs.filter((item: any) => !item.name.includes(target_name))
    store.dispatch("handlerTabsList", tabs);
    if(tabs.length <= 1){
      // 只剩下一项，选中最后一个标签项
      store.dispatch("handlerTabsActiveName", tabs[0].name)
    } else if(tabs.length > 1 && tab_index == 0 && store.state.tabsActiveName == target_name){
        // 删除的项是当前选中的项 且 当前选中项在第一项， 更新 tabsActiveName 选中第一项    
        store.dispatch("handlerTabsActiveName", tabs[0].name)
        return false
    } 
    else if(tabs.length > 1 && store.state.tabsActiveName != target_name){
      // 删除的项不是当前选中的项 不需要更新 tabsActiveName
      return false
    } else if(tabs.length > 1 && store.state.tabsActiveName == target_name){
      // 删除的项是当前选中的项 更新tabsActiveName向前推一个
      store.dispatch("handlerTabsActiveName", tabs[tab_index-1].name)
    }
};


export function get_date(){

}


/*
  导出excel数据
  @params: export_data 需要导出的数据（数组）
           filename 导出的excel文件的文件名
*/
const translate_label = {
  goods_id: "商品id",
  good_name: "商品名称",
  cost: "成本（元）",
  price: "单价（元）",
  profit: "单个利润（元）",
  total_cost: "总成本（元）",
  total_sold_cost: "总售出成本（元）",
  total_price: "总售价（元）",
  total_profit: "总利润（元）",
  quantity_sold: "售出量（件）",
  stock: "库存量（件）",

}
const translate_data = function(data){
   let new_data = []
   data.forEach(function(obj) {
    let new_obj = {}
    for(let key of Object.keys(obj)){
      new_obj[`${translate_label[key]}`] = obj[key]
    }
    new_data.push(new_obj)
   });
   return new_data
}
export function export_excel(export_data, filename){
  const workbook = XLSX.utils.book_new();
  const worksheet = XLSX.utils.json_to_sheet(translate_data(export_data));
  XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1');
  const excelBuffer = XLSX.write(workbook, { bookType: 'xlsx', type: 'array' });
  const blob = new Blob([excelBuffer], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
  saveAs(blob, `${filename}.xlsx`);
}


// 时间戳转日期
export function formatDate(times: number, format: string) {
  let year = new Date(times).getFullYear();
  let month = (new Date(times).getMonth()+1) < 10 ? `0${new Date(times).getMonth()+1}` : new Date(times).getMonth()+1;
  let date = (new Date(times).getDate()) < 10 ? `0${new Date(times).getDate()}` : new Date(times).getDate();
  let hours = (new Date(times).getHours()) < 10 ? `0${new Date(times).getHours()}` : new Date(times).getHours();
  let minutes = (new Date(times).getMinutes()) < 10 ? `0${new Date(times).getMinutes()}` : new Date(times).getMinutes();
  let seconds = (new Date(times).getSeconds()) < 10 ? `0${new Date(times).getSeconds()}` : new Date(times).getSeconds();

  return year + format + month + format + date + ' ' + hours + ":" + minutes + ":" + seconds

} 

/*
  	WAIT_PAYMENT: 待付款
		IN_STOCK: 待发货
		DELIVERED: 已发货
		FINISHED: 已完成
		CANCELLED: 已取消
		OVERDUE: 已过期
*/
export function translateOrderStatus(str: string) {
  return str == "WAIT_PAYMENT" ? "待付款" : 
          str == "IN_STOCK" ? "待发货" : 
            str == "DELIVERED" ? "已发货" : 
              str == "FINISHED" ? "已完成" : 
                str == "CANCELLED" ? "已取消" : 
                  str == "OVERDUE" ? "已过期" : ""
}



